<template>
  <div style="margin: 30px">

    <div>
      <el-row>
        <el-col :span="8">
          <div class="grid-content bg-purple"><h3>{{ articleMethod }}</h3></div>
        </el-col>
        <el-col :span="4" :offset="12">
          <div class="grid-content bg-purple">
            <el-button type="info" icon="el-icon-back" @click="toBack">返回文章列表</el-button>
          </div>
        </el-col>
      </el-row>

    </div>
    <el-form label-width="80px">
      <el-form-item label="标题">
        <el-input v-model="arcticleTitle"></el-input>
      </el-form-item>
      <el-form-item label="介绍">
        <el-input
            type="textarea"
            :rows="3"
            placeholder="请输入内容"
            v-model="articleIntorduce">
        </el-input>
      </el-form-item>

      <el-form-item label="上传封面图片">
        <!--        <input type="file" @change="uploadImg"/><br>-->
        <!--        <img :src="showImg" alt="" style="width:100px"/>-->

        <el-upload
            class="avatar-uploader"
            :action="uploadImageUrl"
            :show-file-list="false"
            :headers="headers"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
          <img v-if="articleImage" :src="articleImage" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>

        <el-button v-if="articleImage" type="danger" icon="el-icon-delete" @click="delImg" circle></el-button>

      </el-form-item>

      <el-form-item label="正文">
        <quill-editor
            v-model="content"
            ref="myQuillEditor"
            :options="editorOption"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @change="onEditorChange($event)"
            @ready="onEditorReady($event)">
        </quill-editor>
      </el-form-item>
    </el-form>
    <div style="overflow: hidden">
      <div style="float: right;">
        <el-button type="warning" @click="resetBody">清空正文</el-button>
        <el-button type="success" @click="doEdit" v-if="articleID!==0">确定编辑文章</el-button>
        <el-button type="success" @click="doCreate" v-else>确定创建文章</el-button>
      </div>
    </div>


  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "articleEditor",
  data() {
    return {
      headers: {
        'token': sessionStorage.getItem("token"),
      },
      content: '',
      articleID: 0,
      arcticleTitle: '',
      articleIntorduce: '',
      articleImage: '',
      editorOption: {
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
            ['blockquote', 'code-block'], // 引用  代码块
            [{header: 1}, {header: 2}], // 1、2 级标题
            [{list: 'ordered'}, {list: 'bullet'}], // 有序、无序列表
            [{script: 'sub'}, {script: 'super'}], // 上标/下标
            [{indent: '-1'}, {indent: '+1'}], // 缩进
            [{direction: 'rtl'}], // 文本方向
            [{size: ['12', '14', '16', '18', '20', '22', '24', '28', '32', '36']}], // 字体大小
            [{header: [1, 2, 3, 4, 5, 6]}], // 标题
            [{color: []}, {background: []}], // 字体颜色、字体背景颜色
            // [{ font: ['songti'] }], // 字体种类
            [{align: []}], // 对齐方式
            ['clean'], // 清除文本格式
            ['image', 'video'] // 链接、图片、视频
          ]
        },
        placeholder: '请输入正文',
      },

      uploadImageUrl: 'http://127.0.0.1:9999/oss/upload',
      // 显示图片的地址
      imageUrl: '',
      imageUrlAdd: '',


    }
  },
  methods: {
    delImg() {
      this.imageUrl = '';
      this.articleImage = '';
    },

    // setImage(url) {
    //   return url.substring(url.lastIndexOf("/") + 1);
    // },
    // handleAvatarSuccessAdd(res, file) {
    //   console.log("res+file")
    //   console.log(res)
    //   console.log(file)
    //   this.imageUrlAdd = URL.createObjectURL(file.raw);
    //   this.articleImage = this.setImage(res);
    // },
    // beforeAvatarUploadAdd(file) {
    //   const isJPG = file.type === 'image/jpeg';
    //   const isLt2M = file.size / 1024 / 1024 < 2;
    //
    //   if (!isJPG) {
    //     this.$message.error('上传头像图片只能是 JPG 格式!');
    //   }
    //   if (!isLt2M) {
    //     this.$message.error('上传头像图片大小不能超过 2MB!');
    //   }
    //   return isJPG && isLt2M;
    // },


    onEditorBlur(quill) {
      console.log('editor blur!', quill)
    },
// 获得焦点事件
    onEditorFocus(quill) {
      console.log('editor focus!', quill)
    },
// 准备富文本编辑器
    onEditorReady(quill) {
      console.log('editor ready!', quill)
    },
// 内容改变事件
    onEditorChange({quill, html, text}) {
      console.log('editor change!', quill, html, text)
      this.content = html
    },
    initArticle() {
      this.$axios({
        url: '/petArticle/' + this.articleID,
        method: 'get',
      }).then(res => {
        if (res.data.code === 200) {
          this.arcticleTitle = res.data.data.title;
          this.articleIntorduce = res.data.data.introduce;
          this.content = res.data.data.body;
          this.articleImage = res.data.data.image;
        }
      })
    },
    resetBody() {
      this.content = '';
    },

    checkData() {
      let li = [];
      if (!this.arcticleTitle) {
        li.push('文章标题')
      }
      if (!this.articleIntorduce) {
        li.push('文章介绍')
      }
      if (!this.articleImage) {
        li.push('文章图片')
      }
      if (!this.content) {
        li.push('文章正文')
      }
      if (li) {
        return li.join();
      } else {
        return '';
      }

      // if(!this.arcticleTitle || !this.articleIntorduce || !this.content){
      //   return false;
      // }
    },
    doEdit() {
      let c = this.checkData();
      if (c) {
        this.$message({
          type: 'warning',
          message: c + '必填',
          duration: 1500,
        });
        return;
      }
      this.$axios({
        method: 'put',
        url: '/petArticle/' + this.articleID,
        data: {
          title: this.arcticleTitle,
          image: this.articleImage,
          introduce: this.articleIntorduce,
          body: this.content,
          display: 0,
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.$message({
            type: 'success',
            message: res.data.msg,
            duration: 1500,
          });
          this.$router.push({
            path: '/petArticleList',
          })

        } else {
          this.$message({
            type: 'info',
            message: res.data.msg,
            duration: 1500,
          });
        }
      })
    },
    doCreate() {
      let c = this.checkData();
      if (c) {
        this.$message({
          type: 'warning',
          message: c + '必填',
          duration: 1500,
        });
        return;
      }
      this.$axios({
        method: 'post',
        url: '/petArticle',
        data: {
          title: this.arcticleTitle,
          image: this.articleImage,
          introduce: this.articleIntorduce,
          body: this.content,
        }
      }).then(res => {
        if (res.data.code === 200) {
          this.$message({
            type: 'success',
            message: res.data.msg,
            duration: 1500,
          });
          this.$router.push({
            path: '/petArticleList',
          })
        } else {
          this.$message({
            type: 'info',
            message: res.data.msg,
            duration: 1500,
          });
        }
      })
    },
    toBack() {
      this.$router.push({
        path: '/petArticleList',
      })
    },

    handleAvatarSuccess(res, file) {
      console.log('handleAvatarSuccess');
      console.log(res);
      this.articleImage = res;
      // this.articleImage = this.imageUrl.substring(this.imageUrl.lastIndexOf("/") + 1);
      // console.log(this.articleImage);

    },
    beforeAvatarUpload(file) {
      this.loadingstate = true;
      let index = file.name.lastIndexOf(".");
      let extension = file.name.substr(index + 1);
      let extensionList = [
        "png",
        "PNG",
        "jpg",
        "JPG",
        "jpeg",
        "JPEG",
        "bmp",
        "BMP",
      ]

      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isLt2M) {
        this.$message({
          message: "封面不可超出2M",
          type: "warning",
          center: true,
        });

        return false;
      } else if (extensionList.indexOf(extension) < 0) {
        this.$message({
          message: "当前文件格式不支持",
          type: "error",
          center: true,
        });

        return false;
      }

    }
  },


  created() {
    console.log('articleeditor')
    console.log(this.$route.query.id)
    this.$route.query.id = this.$route.query.id == null ? 0 : this.$route.query.id;
    this.articleID = parseInt(this.$route.query.id);
    if (this.articleID === 0) {
      this.articleMethod = '创建文章'
    } else {
      this.articleMethod = '编辑文章';
      this.initArticle();
    }
  },

}
</script>

<style>

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}


.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

</style>